﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaskelot.SP.Model.Client;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;
using Kaskelot.SP.Core;
using Kaskelot.SP.Model.Client.Forms;

namespace Kaskelot.SP.Services.Client.Mapping
{
	public static class ClientKursExtensions
	{
		public static ClientKurs ToClientContract(this Kurs entity)
		{
			ClientKurs b = new ClientKurs();

			CopyFromEntity(entity, b, false);

			return b;
		}

		public static ClientKurs ToMinimalClientContract(this Kurs entity)
		{
			ClientKurs b = new ClientKurs();

			CopyFromEntity(entity, b, true);

			return b;
		}

		public static Kurs ToContract(this ClientKurs b)
		{
			Kurs entity = new Kurs();

			CopyToEntity(b, entity);

			return entity;
		}

        public static Kurs UpdateContract(this Kurs Kurs, KursForm form)
        {
            if (Kurs.Id == Guid.Empty)
            {
                Kurs.Id = Guid.NewGuid();
            }

            Kurs.Beskrivning = form.Beskrivning;
			Kurs.KursInfo = form.KursInfo;

            return Kurs;
        }

		private static void CopyFromEntity(Kurs from, ClientKurs to, bool minimal)
		{
			to.Id = from.Id.ToString();
			to.ValId = from.ValId.ToString();

			to.Andrad = from.Andrad != null ? from.Andrad.ToString() : null;
			to.AndradAv = from.AndradAv;
			to.Skapad = from.Skapad != null ? from.Skapad.ToString() : null;
			to.SkapadAv = from.SkapadAv;

			to.KursInfo = from.KursInfo;
			to.Beskrivning = from.Beskrivning;
		}

		private static void CopyToEntity(ClientKurs from, Kurs to)
		{
			to.Id = new Guid(from.Id);
			to.ValId = new Guid(from.ValId);

			if (!String.IsNullOrEmpty(from.Andrad))
				to.Andrad = DateTime.Parse(from.Andrad);
			else
				to.Andrad = null;

			to.AndradAv = from.AndradAv;

			if (from.Skapad != null)
				to.Skapad = DateTime.Parse(from.Skapad);

			to.SkapadAv = from.SkapadAv;

			to.KursInfo = from.KursInfo;
			to.Beskrivning = from.Beskrivning;
		}
	}
}
